import router from './router';
import store from './store';
import NProgress from 'nprogress';
import 'nprogress/nprogress';
import { getToken } from '@/utils/cookie';

NProgress.configure({ showSpinner: false });

const whiteList = ['/login'];

router.beforeEach((to, from, next) => {
  NProgress.start();
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' });
      NProgress.done();
    } else {
      if (store.getters.roles.length === 0) {
        store.dispatch('GetUserInfo').then(() => {
          store.dispatch('GenerateRoutes').then((accessRoutes) => {
            router.addRoutes(accessRoutes);
            next({ ...to, replace: true });
          });
        })
          .catch(() => {
            store.dispatch('LogOut').then(() => {
              next({ path: '/login', query: { redirect: to.fullPath } });
            });
          });
      } else {
        next();
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next(`/login?redirect=${to.fullPath}`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
